package com.fingard.dsp.bank.directbank.ccb41;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;

/**
 * Created by F on 2018/7/4.
 */
public class Des3 {
    private static final String Algorithm = "DESede"; // 定义 加密算法,可用
    // DES,DESede,Blowfish
    // keybyte为加密密钥，长度为24字节
    // src为被加密的数据缓冲区（源）
    //定义加密算法，有DES、DESede(即3DES)、Blowfish
    /**
     * 加密方法
     * @param src 源数据的字节数组
     * 		  PASSWORD_CRYPT_KEY 3DES加密key
     * @return
     */
    public static byte[] encryptMode(byte[] src, String PASSWORD_CRYPT_KEY) {
        try {
            SecretKey deskey = new SecretKeySpec(build3DesKey(PASSWORD_CRYPT_KEY), Algorithm);    //生成密钥
            Cipher c1 = Cipher.getInstance(Algorithm);    //实例化负责加密/解密的Cipher工具类
            c1.init(Cipher.ENCRYPT_MODE, deskey);    //初始化为加密模式
            return c1.doFinal(src);
        } catch (java.security.NoSuchAlgorithmException e1) {
            e1.printStackTrace();
        } catch (javax.crypto.NoSuchPaddingException e2) {
            e2.printStackTrace();
        } catch (java.lang.Exception e3) {
            e3.printStackTrace();
        }
        return null;
    }

    /**
     * 解密函数
     * @param src 密文的字节数组
     * 		  PASSWORD_CRYPT_KEY 3DES解密key
     * @return
     */
    public static byte[] decryptMode(byte[] src, String PASSWORD_CRYPT_KEY) {
        try {
            SecretKey deskey = new SecretKeySpec(build3DesKey(PASSWORD_CRYPT_KEY), Algorithm);
            Cipher c1 = Cipher.getInstance(Algorithm);
            c1.init(Cipher.DECRYPT_MODE, deskey);    //初始化为解密模式
            return c1.doFinal(src);
        } catch (java.security.NoSuchAlgorithmException e1) {
            e1.printStackTrace();
        } catch (javax.crypto.NoSuchPaddingException e2) {
            e2.printStackTrace();
        } catch (java.lang.Exception e3) {
            e3.printStackTrace();
        }
        return null;
    }

    /*
     * 根据字符串生成密钥字节数组
     * @param keyStr 密钥字符串
     * @return
     * @throws UnsupportedEncodingException
     */
    public static byte[] build3DesKey(String keyStr) throws UnsupportedEncodingException{
        byte[] key = new byte[24];    //声明一个24位的字节数组，默认里面都是0
        byte[] temp = keyStr.getBytes("UTF-8");    //将字符串转成字节数组

        /**
         * 执行数组拷贝
         * System.arraycopy(源数组，从源数组哪里开始拷贝，目标数组，拷贝多少位)
         */
        if(key.length > temp.length){
            //如果temp不够24位，则拷贝temp数组整个长度的内容到key数组中
            System.arraycopy(temp, 0, key, 0, temp.length);
        }else{
            //如果temp大于24位，则拷贝temp数组24个长度的内容到key数组中
            System.arraycopy(temp, 0, key, 0, key.length);
        }
        return key;
    }

    public static void main(String[] args) {
        //String msg = "123456789abcdefghi。jklmnLPOKM|NHK储值卡aa MML12b你好电灯泡，";
        String msg = "8001" + "abcdefghijkl" + "12国456中8";
        msg = "8002a中1";
        System.out.println("【加密前】：" + msg);
        String key = "cKK8RcFXyBVPW6TBbeykj3CivEXBV8gV";
        String key1 = "1cKK8RcFXyBVPW6TBbeykj3CivEXBV8gV";

        //加密
        byte[] secretArr = null;
        try {
            secretArr = encryptMode(msg.getBytes("UTF-8"), key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.print("【加密字符串】：");
        System.out.println("加密之后的字符串长度:"+secretArr.length);
        for (int i = 0; i < secretArr.length; i++) {
            System.out.print(secretArr[i] + " ");
        }
        System.out.println("");
        //System.out.println("【加密后】：" + new String(secretArr));


        System.out.print("【解密字符串】：");

        //解密
        byte[] bytes =new byte[secretArr.length-1];
        System.arraycopy(secretArr,0,bytes,0,bytes.length);
        System.out.println(new String (secretArr));
        System.out.println(new String (bytes));
        byte[] myMsgArr = decryptMode(bytes, key);

        for (int i = 0; i < myMsgArr.length; i++) {
            System.out.print(myMsgArr[i] + " ");
        }
        System.out.println("");

        try {
            System.out.println("【解密后】：" + new String(myMsgArr, "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
